package com.yuyu.qingmangmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuyu.common.to.es.SkuEsModel;
import com.yuyu.qingmangmall.search.config.QingmangElasticsSarchConfig;
import com.yuyu.qingmangmall.search.constant.EsConstant;
import com.yuyu.qingmangmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ProductSaveServiceImpl  implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        // 保存到es
        // 1.给es中建立索引。product，建立好映射关系。

        // 2.给es中保存这些数据
        // BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        // 将商品数据批量传入es
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求
            IndexRequest index = new IndexRequest(EsConstant.PRODUCT_INDEX);
            index.id(skuEsModel.getSkuId().toString());
            String string = JSON.toJSONString(skuEsModel);
            IndexRequest source = index.source(string, XContentType.JSON);
            bulkRequest.add(source);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, QingmangElasticsSarchConfig.COMMON_OPTIONS);

//        BulkItemResponse[] items = bulk.getItems();
        // TODO 如果批量错误
        boolean b = bulk.hasFailures(); // 失败了会返回 true  response.isFailed()  return true;
        if (b){
            BulkItemResponse[] items = bulk.getItems();
            List<String> list = new ArrayList<>();
            for (BulkItemResponse item : items) {
                String id = item.getId();
                list.add(id);
            }
            log.error("商品上架错误{}",list);
        }
        return !b;
    }
}
